package com.caowei.weicimpress.weicimpress;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.caowei.weicimpress.weicimpress.widget.ActionItem;
import com.caowei.weicimpress.weicimpress.widget.LeftActionbarDropdownListWidget;
import com.caowei.weicimpress.weicimpress.widget.MyListView;
import com.caowei.weicimpress.weicimpress.widget.Toast;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;

/**
 * Created by caoweiPc on 2014/7/15.
 */
public abstract class ActionBarBaseFragment extends BaseFragment implements AdapterView.OnItemClickListener,
        FragHandlerHub.UpdateUI<MyDataList> ,AdapterView.OnItemLongClickListener,View.OnClickListener{
    private final static String TAG=ActionBarBaseFragment.class.getSimpleName();
    private final static String CURRENTPATH_KEY="CURRENTPATH";
    protected File rootFile;
    @InjectView(R.id.rootfilename)
    TextView rootfilename;
    @InjectView(R.id.list)
    MyListView mListView;
    @InjectView(R.id.footer1)
    LinearLayout footer1;
    @InjectView(R.id.footer2)
    LinearLayout footer2;
    @InjectView(R.id.numoffiles)
    TextView numoffiles;
    @InjectView(R.id.spacesize)
    TextView spacesize;
    @InjectView(R.id.footer2_4)
    TextView footer2_4;
    @InjectView(R.id.footer2_3)
    TextView footer2_3;
    @InjectView(R.id.footer2_1)
    TextView footer2_1;
    @InjectView(R.id.footer2_2)
    TextView footer2_2;
    @InjectView(R.id.fixedlistheader)
    LinearLayout fixedlistheader;
    @InjectView(R.id.progress)
    LinearLayout progress;
    @InjectView(R.id.innerprocess)
    ImageView innerprocess;
    @InjectView(R.id.tip)
    TextView tip;
    @InjectView(R.id.content)
    RelativeLayout content;
    @InjectView(R.id.footer3)
    LinearLayout footer3;
    @InjectView(R.id.dirOk)
    TextView dirOk;
    @InjectView(R.id.dirCancel)
    TextView dirCancel;
    protected RelativeLayout actionbarLayout;

    protected ExecuteFileHandler executeFileHandler;
    private LinearLayout footer;
    @InjectView(R.id.cover)
    LinearLayout cover_layout;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }
    protected ActionItemWithFileInfoBean actionItemWithFileInfoBean;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.filefragment,container,false);
        ButterKnife.inject(this, v);

        if(Build.VERSION_CODES.HONEYCOMB>=Build.VERSION.SDK_INT){
            Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.footer_bg);
            int argb= bitmap.getPixel(bitmap.getWidth()/2,bitmap.getHeight()/2);
            footer1.setBackgroundColor(argb);
            footer2.setBackgroundColor(argb);
            footer3.setBackgroundColor(argb);

            Bitmap bitmap1= BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.cover_bg);

            progress.setBackgroundColor(bitmap1.getPixel(bitmap1.getWidth()/2,
                    bitmap1.getHeight()/2));
        }


        FileInfoAdapter adapter=new FileInfoAdapter(this);

//        View header=LayoutInflater.from(getActivity()).inflate(
//                R.layout.filefragmentitem,mListView,false);
//        ((ImageView)header.findViewById(R.id.img)).setImageResource(R.drawable.fatherico);
//
//        ((TextView)header.findViewById(R.id.fileName)).setText(getActivity().
//                getResources().getString(R.string.fatherdir));
//        ((TextView)header.findViewById(R.id.time_authrity)).setText(
//                getActivity().getResources().getString(R.string.fatherdir1));
//
//        mListView.addHeaderView(header);
//
//        HeaderViewListAdapter listAdapter=new HeaderViewListAdapter(null,null,adapter);
        /*LinearLayout footer=new LinearLayout(this.getActivity());
        AbsListView.LayoutParams params=
                new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,64);
        footer.setLayoutParams(params);*/
//        TextView
//        mListView.addFooterView(footer);
        footer= (LinearLayout) LayoutInflater.
                from(this.getActivity()).inflate(R.layout.filefragmentitem_footer,mListView,false);
        mListView.addFooterView(footer);
        mListView.setAdapter(adapter);
        mListView.removeFooterView(footer);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        Activity hostActivity=getActivity();
        if(GainActionbarLayout.class.isAssignableFrom(hostActivity.getClass())){
            actionbarLayout= ((GainActionbarLayout)hostActivity).gainActionbarLayout();
        }

        if(Utils.DEBUG){
            Log.d(TAG,"savedInstanceState="+savedInstanceState);
            if(savedInstanceState!=null){
                Log.d(TAG,savedInstanceState.getString(CURRENTPATH_KEY));
            }
        }
        if(savedInstanceState!=null){
            refreshFromPath(savedInstanceState.getString(CURRENTPATH_KEY),true);
        }else{
            refreshFromRootFile();
        }

        HeaderViewListAdapter listAdapter= (HeaderViewListAdapter) mListView.getAdapter();
        OnActivityCreatedListener listener= (OnActivityCreatedListener)listAdapter.getWrappedAdapter();
        listener.onActivityCreated();

        progress.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String currentPath=findPathPathOnAtionbarLayout().getText().toString();
        outState.putString(CURRENTPATH_KEY,currentPath);
    }

    public void enableFragment(boolean enable){
        if(cover_layout.getVisibility()==View.VISIBLE&&!enable){
            cover_layout.setVisibility(View.GONE);
        }else if(cover_layout.getVisibility()!=View.VISIBLE&&enable){
            cover_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void refresh(){
//        LinearLayout pathlayout=findPathlayoutOnAtionbarLayout();
        TextView textView=findPathPathOnAtionbarLayout();
//        LeftActionbarDropdownListWidget listWidget= (LeftActionbarDropdownListWidget) pathlayout.getTag();
        executeHandlerList(Utils.normalizePath(new StringBuilder(textView.getText()).toString()),
                FragHandlerHub.CLICKSOURCE.NORMAL);
    }

    public void refreshFromPath(String path,boolean refresh){
        String path1=Utils.normalizePath(path);
        String currentPath= findPathPathOnAtionbarLayout().getText().toString();
        if(path1.equals(currentPath)&&!refresh){
            return;
        }
        executeHandlerList(Utils.normalizePath(path), FragHandlerHub.CLICKSOURCE.NORMAL);
    }

    public void refreshFromPath(String path){
        String path1=Utils.normalizePath(path);
        String currentPath= findPathPathOnAtionbarLayout().getText().toString();
        if(!path1.equals(currentPath)){
            return;
        }
        executeHandlerList(Utils.normalizePath(path), FragHandlerHub.CLICKSOURCE.NORMAL);
    }

    public void refreshFromRootFile(){
        executeHandlerList(null, FragHandlerHub.CLICKSOURCE.NORMAL);
    }

    protected void executeHandlerList(String path,FragHandlerHub.CLICKSOURCE clicksource){
        if(executeFileHandler==null){
            executeFileHandler=ExecuteFileHandler.getInstance();
        }
        if(rootFile!=null){
            FragHandlerHub hub=new FragHandlerHub();
            hub.setClickSource(clicksource);
            hub.setUpdateUI(this);
            FileInfoBean fileInfoBean=new FileInfoBean();
            fileInfoBean.setRootFile(rootFile);
            fileInfoBean.setParentPath(path);
            fileInfoBean.setDir(true);
            //进度条 显视
            showCoverProgress(true,getActivity().getResources().getString(R.string.refreshing));

            executeFileHandler.execute(fileInfoBean,FileHandler.OperType.LIST,hub);

        }
    }

    protected void showCoverProgress(boolean show,String msg){
        tip.setText(msg);
        if(show){
            progress.setVisibility(View.VISIBLE);
            AnimationDrawable mAnimationDrawable = (AnimationDrawable) innerprocess.getBackground();
            mAnimationDrawable.start();
        }else{
            progress.setVisibility(View.GONE);
            AnimationDrawable mAnimationDrawable = (AnimationDrawable) innerprocess.getBackground();
            mAnimationDrawable.stop();
        }
    }

    protected abstract void init();

    public int performBack(){
        String parentPath= Utils.normalizePath((String) fixedlistheader.getTag());
        parentPath= Utils.normalizePath(parentPath);
        if(parentPath.equals(File.separator)||TextUtils.isEmpty(parentPath)){
          return -1;
        }
        fixedlistheader.performClick();
        return 0;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnItemClick(R.id.list)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileInfoAdapter.ViewHolder viewHolder= (FileInfoAdapter.ViewHolder) view.getTag();
        //todo  以后前后插入代码

        FileInfoBean bean= viewHolder.getBean();
        if(bean.isDir()){
            footer2_3.performClick();
            String path=bean.getParentPath()+File.separator+bean.getFileName()+File.separator;
            Log.d(TAG,path);
            executeHandlerList(Utils.normalizePath(path), FragHandlerHub.CLICKSOURCE.NORMAL);
            return;
        }else if(!bean.isDir()){
            //todo
        }
        onSubItemClick(parent, view, position, id);
    }

    @Override
    @OnItemLongClick(R.id.list)
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
        //todo 实现对单个文件的操作 如压缩  解压
        FileInfoAdapter.ViewHolder vh= (FileInfoAdapter.ViewHolder) view.getTag();
        FileInfoBean fileInfoBean=vh.getBean();
        actionItemWithFileInfoBean.bean=fileInfoBean;
        if(actionItemWithFileInfoBean.actionItems==null){
            String[] arr=getItemLongClickMenu(fileInfoBean);
            actionItemWithFileInfoBean.actionItems=new ArrayList<GenerateDialog.ActionItem>();
            for(int i=0;i<arr.length;i++){
                String name=arr[i];
                final int j=i;
                GenerateDialog.ActionItem actionItem=new GenerateDialog.ActionItem();
                actionItem.setName(name);
                actionItem.setCallback(new GenerateDialog.Callback() {
                    @Override
                    public void callback(Object[] t) {
                        exeDialogOper(j, actionItemWithFileInfoBean.bean);
                    }
                });
                actionItemWithFileInfoBean.actionItems.add(actionItem);
            }
        }
        GenerateDialog.createSelectOperDialog(getActivity().getResources().getString(R.string.selectoper),
                getActivity(),actionItemWithFileInfoBean.actionItems).show();
        return true;
    }

    protected abstract String[] getItemLongClickMenu(FileInfoBean bean);
    protected abstract void exeDialogOper(int position, FileInfoBean bean);

    protected abstract void  onSubItemClick(AdapterView<?> parent, View view, int position, long id) ;

    protected abstract void  onSubLongItemClick(AdapterView<?> parent, View view, int position, long id) ;

    @OnClick({R.id.footer2_2,R.id.footer2_3,R.id.footer2_1,R.id.footer2_4,R.id.fixedlistheader,R.id.dirOk,R.id.dirCancel})
    @Override
    public void onClick(View v) {
        int id=v.getId();
        //todo
        switch (id){
            case R.id.footer2_3:
                v.setEnabled(false);
                mListView.cancleAllSelectedCheckbox();
                v.setEnabled(true);
                break;
            case R.id.footer2_1:
                break;
            case R.id.footer2_4:
                break;
            case R.id.fixedlistheader:
                v.setEnabled(false);
                String parentPath= Utils.normalizePath((String) v.getTag());
                if(parentPath.equals(File.separator)||TextUtils.isEmpty(parentPath)){
                    Toast.makeText(getActivity(),getActivity().getResources().getString(R.string.topdir),
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                parentPath=Utils.drop2SlashOfStr(parentPath);
                int index= parentPath.lastIndexOf(File.separator);
                if(index!=-1){
                    parentPath= parentPath.substring(0,index);
                }else{
                    parentPath=File.separator;
                }
                parentPath=Utils.normalizePath(parentPath);
                executeHandlerList(parentPath,FragHandlerHub.CLICKSOURCE.NORMAL);
                break;
        }
    }

    @Override
    public void updateUI(MyDataList result,FragHandlerHub.CLICKSOURCE clickSource){
        HeaderViewListAdapter listAdapter= (HeaderViewListAdapter) mListView.getAdapter();
        if(result==null){
            result=new MyDataList();
        }
        FileInfoAdapter adapter= (FileInfoAdapter) listAdapter.getWrappedAdapter();
        adapter.setmData(result.getFileInfoBeans());
        int item_count= adapter.getCount();
        float total_h=(item_count+1)*getActivity().getResources().getDimension(R.dimen.filefragmentitem_h);

        int content_h= getActivity().getWindow().getDecorView().
                findViewById(Window.ID_ANDROID_CONTENT).getHeight();
        float listview_h= content_h-getActivity().getResources().getDimension(R.dimen.footer_h);
        if(total_h<=listview_h){
            mListView.removeFooterView(footer);
        }else if(total_h>listview_h){
            if(mListView.getFooterViewsCount()==0){
                mListView.addFooterView(footer);
            }
        }
        adapter.dataNotifySetChanged();

        showCoverProgress(false,null);
        fixedlistheader.setEnabled(true);
        //========================

        if(footer1.getVisibility()!=View.VISIBLE){
            footer1.setVisibility(View.VISIBLE);
        }
        int n1= result.getNumOfDirs()==-1?0:result.getNumOfDirs(),
                n2=result.getNumOfFiles()==-1?0:result.getNumOfFiles();
        String str=getActivity().getResources().getString(R.string.numoffileanddir,n1,n2);
        numoffiles.setText(str);

        BigDecimal n4=result.getAllSpace();

        str=getActivity().getResources().getString(R.string.sizeoffileanddir,
                getActivity().getResources().getString(R.string.omit), Utils.normalSizeStr(n4));
        spacesize.setText(str);

        String parentPath= result.getParentPath();
        parentPath=Utils.drop2SlashOfStr(parentPath);
        String[] pathArr=null;
        if(!TextUtils.isEmpty(parentPath)&&!parentPath.equals(File.separator)){
            pathArr=parentPath.split(File.separator);
        }
        pathArr=Utils.concatAll(new String[]{File.separator},pathArr);
        fixedlistheader.setTag(result.getParentPath());
        if(clickSource.equals(FragHandlerHub.CLICKSOURCE.NORMAL)){
            firePathlayoutUpdate(pathArr);
        }

        if(rootFile!=null){
            String rootfileName= getActivity().getResources().getString(R.string.rootfile,
                    rootFile.getName());
            rootfilename.setText(rootfileName);
        }

       /* if(footer2.getVisibility()==View.VISIBLE){
            footer2.setVisibility(View.GONE);
        }

        if(footer3.getVisibility()==View.VISIBLE){
            footer3.setVisibility(View.GONE);
        }
        mListView.setLongClickable(true);
        enableMlistViewCheckbox(true);*/
    }


    protected abstract LinearLayout findPathlayoutOnAtionbarLayout();
    protected abstract TextView findPathPathOnAtionbarLayout();
    /*
    * 触发 标题栏上 路径 更新
    * */
    private void firePathlayoutUpdate(String[] pathArr){

        LinearLayout pathlayout=findPathlayoutOnAtionbarLayout();
        final TextView textView=findPathPathOnAtionbarLayout();
        LeftActionbarDropdownListWidget listWidget= (LeftActionbarDropdownListWidget) pathlayout.getTag();

        StringBuilder sb=new StringBuilder();
        listWidget.clearAllActionItem();
        for(final String path:pathArr){
            final ActionItem item=new ActionItem();
            item.setIcoId(R.drawable.dropdirico);
            item.setMenuName(path);
            item.setCallback(new ActionItem.Callback() {
                @Override
                public void callback(Object... params) {
                    Log.d(TAG, "callback");
                    //todo
                    String currentPath=new  StringBuilder(textView.getText()).toString();
                    String currentPath1= (String) item.getExtra("path");
                    Log.d(TAG,"currentPath="+currentPath+" currentPath1="+currentPath);
                  /*  if(currentPath.equals(currentPath1)){
                        Log.d(TAG,"路径不变");
                        return;
                    }*/
                    //todo  出错
                    currentPath1=Utils.normalizePath(currentPath1);
                    executeHandlerList(currentPath1, FragHandlerHub.CLICKSOURCE.ACTIONBAR);
                }
            });
            sb.append(path).append(File.separator);
            item.putExtra("path",Utils.normalizePath(sb.toString()));
            listWidget.addActionItem(item);
        }
        textView.setText(Utils.normalizePath(sb.toString()));
        listWidget.performLastItemClick();
    }

    protected void enableMlistViewCheckbox(boolean enable){
        HeaderViewListAdapter hAdaper= (HeaderViewListAdapter) mListView.getAdapter();
        FileInfoAdapter fileInfoAdapter= (FileInfoAdapter) hAdaper.getWrappedAdapter();
        List<CheckBox> checkBoxes= fileInfoAdapter.getCheckBoxList();
        for (CheckBox checkBox:checkBoxes){
            checkBox.setEnabled(enable);
        }
    }

    protected List<FileInfoBean> getSelectedItems(){
        HeaderViewListAdapter headerViewListAdapter= (HeaderViewListAdapter) mListView.getAdapter();
        FileInfoAdapter adapter= (FileInfoAdapter) headerViewListAdapter.getWrappedAdapter();
        Map<Integer,FileInfoAdapter.CheckBoxBoolean> map= adapter.getSelectedCheckboxes();
        Set<Integer> set= map.keySet();
        List<FileInfoBean> beans=new ArrayList<FileInfoBean>();
        for (int i:set){
            FileInfoBean bean= adapter.getItem(i);
            beans.add(bean);
        }
        return beans;
    }

    public List<FileInfoBean> getDataResult(){
        HeaderViewListAdapter headerViewListAdapter= (HeaderViewListAdapter) mListView.getAdapter();
        FileInfoAdapter adapter= (FileInfoAdapter) headerViewListAdapter.getWrappedAdapter();
        List<FileInfoBean> result=new ArrayList<FileInfoBean>(adapter.getmData());
        return result;
    }

    protected void cancelAllMlistViewCheckbox(){
        HeaderViewListAdapter hAdaper= (HeaderViewListAdapter) mListView.getAdapter();
        FileInfoAdapter fileInfoAdapter= (FileInfoAdapter) hAdaper.getWrappedAdapter();
        Map<Integer, FileInfoAdapter.CheckBoxBoolean> checkBoxes= fileInfoAdapter.getSelectedCheckboxes();
        Set<Integer> keies=checkBoxes.keySet();
        if(keies.size()>0){
            footer2_3.performClick();
        }
    }

    protected void enablefooterBtnes(){
        if(!footer2_1.isEnabled()){
            footer2_1.setEnabled(true);
        }
        if(!footer2_2.isEnabled()){
            footer2_2.setEnabled(true);
        }
        if(!footer2_3.isEnabled()){
            footer2_3.setEnabled(true);
        }
        if(!footer2_4.isEnabled()){
            footer2_4.setEnabled(true);
        }
        if(!dirOk.isEnabled()){
            dirOk.setEnabled(true);
        }
        if(!dirCancel.isEnabled()){
            dirCancel.setEnabled(true);
        }
    }

    public void setRootFile(File rootFile){
        this.rootFile=rootFile;
    }

    public File getRootFile(){
        return this.rootFile;
    }

    public static interface OnActivityCreatedListener{
        public void onActivityCreated();
    }

    public static interface GainActionbarLayout{
        public RelativeLayout gainActionbarLayout();
    }




    public static interface OnRefreshFragment{
        public void onRefresh(int fragmentIndex);
    }


    protected static class ActionItemWithFileInfoBean{
        FileInfoBean bean;
        List<GenerateDialog.ActionItem> actionItems;
    }
}
